package com.zg.system.auth;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.zg.common.cache.service.impl.RedisCacheServiceImpl;
import com.zg.common.core.R;
import com.zg.common.web.Req;
import com.zg.common.core.User;
import com.zg.common.core.dao.auth.AuthUser;
import com.zg.common.core.dao.auth.AuthUserDao;
import com.zg.common.core.util.MailUtil;
import com.zg.system.auth.vo.BindMailVo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;

/**
 * @author Zxb
 */
@RestController
@RequiredArgsConstructor
public class EmailController {
    private final AuthUserDao userDao;
    private final RedisCacheServiceImpl redisService;
    private final JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    @PostMapping("/user/email/send")
    public R sendMail(@RequestBody String to) {
        if (StrUtil.isBlank(to)) {
            return R.error("请设置目标邮箱地址");
        }
        if (!MailUtil.isEmail(to)) {
            return R.error("请设置正确的邮箱地址");
        }
        String code = RandomUtil.randomString(8);
        User u = Req.getCurrUser();
        AuthUser user = userDao.getById(u.getId());
        String key = user.getUsername() + ":email:code";
        redisService.addKey(key, code, 300L);
        String subject = "绑定邮箱操作验证码";
        String text = "您当前正在尝试绑定新的邮箱，验证码为：" + code;
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);
        mailSender.send(message);
        return R.success();
    }

    @PostMapping("/user/email/bind")
    public R bindEmail(@RequestBody @Valid BindMailVo bindMailVo) {
        User u = Req.getCurrUser();
        AuthUser user = userDao.getById(u.getId());
        String code = bindMailVo.getCode();
        String key = user.getUsername() + ":email:code";
        String value = redisService.findValue(key);
        if (!code.equals(value)) {
            return R.error("验证码错误");
        }
        redisService.delKey(key);
        user.setEmail(bindMailVo.getEmail());
        userDao.updateById(user);
        return R.success();
    }
}
